import datetime
import  logging
from django.db.models.signals import post_save, post_init, post_delete
from django.dispatch import receiver

from cards.models import CustomerCard, Card
from finance.api.utils import get_account, create_journal, remove_journal


logger = logging.getLogger("django")


@receiver(post_init, sender=CustomerCard)
def receipt_init(instance, **kwargs):
    instance.old_sale_class = instance.sale_class


@receiver(post_save, sender=CustomerCard)
def handle_customer_card(sender, instance, created, **kwargs):
    """客户优惠卡"""
    logger.info('handle_customer_card')

    if created:
        Card.objects.filter(id=instance.card_id).update(status=1)

    if instance.sale_class == 1:

        data = {
            'order_no': instance.code,
            'customer': instance.customer or None,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': '客户优惠卡销售',
            'money': instance.actual_money,
            'balance': instance.account.balance,
            'user': instance.user or None,
            'desc': instance.remark,
            'created': created,
        }
        logger.info(data)
        # 流水账记录
        create_journal(**data)
    elif instance.old_sale_class == 1:
        remove_journal(instance.code)


@receiver(post_delete, sender=CustomerCard)
def handle_customer_card_del(sender, instance, **kwargs):
    """删除客户优惠卡"""
    Card.objects.filter(id=instance.card_id).update(status=0)
    if instance.sale_class == 1:
        remove_journal(instance.code)


